<template>
  <div class="container">
    <div class="header">
      <h1 class="text-2xl font-bold">课程分班管理</h1>
      <h3 class="text-gray-500 text-base mt-1">根据上课人数进行合理分班，优化教学资源分配</h3>
    </div>

    <!-- 课程基础信息卡片 -->
    <el-card class="mb-6 rounded-lg shadow-md" v-if="tableData.length">
      <template #header>
        <div class="flex flex-col">
          <h2 class="text-2xl font-bold leading-tight">
            {{ tableData[0].courseName }}
          </h2>
          <p class="text-gray-500 text-sm mt-1">
            课程编号: {{ tableData[0].courseCode }}
          </p>
        </div>
      </template>

      <div class="p-4 space-y-4">
        <!-- 第一行：开课学院、学期、总学时、学分 -->
        <el-row :gutter="24" class="mb-4">
          <el-col :span="6">
            <div class="info-item">
              <el-icon :size="24" color="var(--el-color-primary)">
                <School />
              </el-icon>
              <div class="info-content">
                <span class="info-label">开课学院</span>
                <span class="info-value">{{ tableData[0].departmentId || tableData[0].departmentName || '未知学院' }}</span>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <el-icon :size="24" color="var(--el-color-primary)">
                <Calendar />
              </el-icon>
              <div class="info-content">
                <span class="info-label">学期</span>
                <dict-tag :options="semester" :value="tableData[0].semester" />
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <el-icon :size="24" color="var(--el-color-primary)">
                <Clock />
              </el-icon>
              <div class="info-content">
                <span class="info-label">总学时</span>
                <span class="info-value">{{ tableData[0].totalHours || 0 }} 小时</span>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <el-icon :size="24" color="var(--el-color-primary)">
                <Document />
              </el-icon>
              <div class="info-content">
                <span class="info-label">学分</span>
                <span class="info-value">{{ tableData[0].credits || 0 }} 学分</span>
              </div>
            </div>
          </el-col>
        </el-row>

        <!-- 第二行：课程类型、英文名称、选课人数、当前班级数 -->
        <el-row :gutter="24">
          <el-col :span="6">
            <div class="info-item">
              <el-icon :size="24" color="var(--el-color-primary)">
                <Menu />
              </el-icon>
              <div class="info-content">
                <span class="info-label">课程类型</span>
                <span class="info-value">{{ getCourseCharacterLabel() }}</span>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <el-icon :size="24" color="var(--el-color-primary)">
                <ChatLineSquare />
              </el-icon>
              <div class="info-content">
                <span class="info-label">课程英文名称</span>
                <span class="info-value">{{ tableData[0].courseNameEn || '无' }}</span>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <el-icon :size="24" color="var(--el-color-primary)">
                <User />
              </el-icon>
              <div class="info-content">
                <span class="info-label">选课人数</span>
                <span class="info-value">{{ totalEnrollmentCount + ' 人' }}</span>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <el-icon :size="24" color="var(--el-color-primary)">
                <Tools />
              </el-icon>
              <div class="info-content">
                <span class="info-label">当前班级数</span>
                <span class="info-value">{{ classCount || 0 }} 个班级</span>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 培养方案详情区域 -->
    <div class="header mt-8">
      <h1>对应培养方案详情</h1>
    </div>
    <el-card
        class="mb-6 rounded-lg shadow-md program-detail-card"
        v-for="(program, index) in filteredTrainingManagementList"
        :key="program.id"
        :style="index > 0 ? 'margin-top: 20px;' : ''"
    >
      <div class="p-4 space-y-4">
        <!-- 第一行：培养方案名称、编号、类型、专业 -->
        <el-row :gutter="24" class="mb-4">
          <el-col :span="6">
            <div class="info-item">
              <el-icon :size="24" color="var(--el-color-primary)">
                <Document />
              </el-icon>
              <div class="info-content">
                <span class="info-label program-info-label">培养方案名称</span>
                <span class="info-value program-info-value">{{ program.name || '未知方案' }}</span>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <el-icon :size="24" color="var(--el-color-primary)">
                <Document />
              </el-icon>
              <div class="info-content">
                <span class="info-label program-info-label">方案编号</span>
                <span class="info-value program-info-value">{{ program.programCode || '无编号' }}</span>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <el-icon :size="24" color="var(--el-color-primary)">
                <Menu />
              </el-icon>
              <div class="info-content">
                <span class="info-label program-info-label">培养方案类型</span>
                <dict-tag
                    :options="culture_program_type"
                    :value="program.cultureProgramType"
                    class="program-dict-tag"
                    placeholder="未知类型"
                />
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item major-info-item">
              <el-icon :size="24" color="var(--el-color-primary)">
                <Document />
              </el-icon>
              <div class="info-content">
                <span class="info-label program-info-label">专业（所属学院）</span>
                <div class="info-value program-info-value">
                  <div v-if="subjectLoadingMap.get(program.id)" class="program-info-tip">加载中学科信息...</div>
                  <div v-else-if="!programSubjectMap.get(program.id)?.length" class="program-info-tip">暂无学科研究方向信息</div>
                  <div v-else class="mt-1 subject-info-container">
                    <div v-for="(subject, idx) in programSubjectMap.get(program.id)" :key="idx">
                      <p class="font-medium subject-info-p">
                        一级学科：{{ subject.firstSubjectName || '未知一级学科' }}（{{ subject.firstSubjectCode || '' }}）
                      </p>
                      <p v-if="subject.secondSubjectCode" class="ml-2 subject-info-p">
                        二级学科：{{ subject.secondSubjectName || '未知二级学科' }}（{{ subject.secondSubjectCode || '' }}）
                      </p>
                      <div class="ml-2 mt-0.5 subject-info-dir">
                        <span class="text-gray-500">研究方向：</span>
                        <span v-for="(dir, dirIdx) in subject.directionReturnVoList" :key="dirIdx">
                          {{ dir.name || '未知方向' }}（{{ dir.researchDirectionCode || '' }}）
                          <span v-if="dirIdx < subject.directionReturnVoList.length - 1">、</span>
                        </span>
                      </div>
                      <p class="mt-0.5 subject-info-p">（{{ getCollegeName(program.collegeId, collegeLoaded) }}）</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>

        <!-- 第二行：年级、对应人数、查看按钮 -->
        <el-row :gutter="24">
          <el-col :span="6">
            <div class="info-item">
              <el-icon :size="24" color="var(--el-color-primary)">
                <Calendar />
              </el-icon>
              <div class="info-content">
                <span class="info-label program-info-label">年级</span>
                <dict-tag :options="grade" :value="program.grade" class="program-dict-tag" />
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <el-icon :size="24" color="var(--el-color-primary)">
                <UserFilled />
              </el-icon>
              <div class="info-content">
                <span class="info-label program-info-label">对应人数</span>
                <span class="info-value program-info-value">{{ program.amount || 0 }} 人</span>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item action-item">
              <el-button
                  type="primary"
                  size="small"
                  icon="el-icon-user"
                  @click="handleViewProgramStudents(program.id)"
                  class="program-view-btn"
              >
                查看学生名单
              </el-button>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 分班规则设置区域 -->
    <div class="rule-container" v-if="!isStatusActive">
      <div class="rule-header flex items-center mb-4">
        <el-icon :size="20" color="var(--el-color-primary)">
          <Menu />
        </el-icon>
        <h2 class="text-lg font-semibold ml-2">分班规则设置</h2>
      </div>

      <!-- 班级人数与数量设置（修复：输入框去空格） -->
      <el-row :gutter="24" class="mb-6">
        <el-col :span="12">
          <div class="form-item">
            <label class="block text-sm font-medium mb-1">最大班级人数</label>
            <el-input
                v-model="formData.maxClassSize"
                type="number"
                placeholder="请输入最大班级人数（如30-60）"
                clearable
                size="small"
                min="1"
                @input="formData.maxClassSize = formData.maxClassSize.replace(/[^0-9]/g, '').trim()"
            />
            <p class="text-xs text-gray-500 mt-1">建议设置在30-60人之间，根据课程性质调整</p>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="form-item">
            <label class="block text-sm font-medium mb-1">开班数量</label>
            <el-input
                v-model="formData.numClasses"
                type="number"
                placeholder="请输入开班数量"
                clearable
                size="small"
                min="1"
                @input="formData.numClasses = formData.numClasses.replace(/[^0-9]/g, '').trim()"
            />
            <p class="text-xs text-gray-500 mt-1">系统将根据最大班级人数和总人数自动计算合理数值</p>
          </div>
        </el-col>
      </el-row>

      <!-- 分班方式选择 -->
      <div class="form-item mb-6">
        <label class="block text-sm font-medium mb-2">分班方式</label>
        <div class="flex gap-4">
          <el-button
              type="primary"
              plain
              @click="divisionMode = 'auto'"
              :class="divisionMode === 'auto' ? 'selected-mode' : ''"
              size="large"
          >
            自动分班
          </el-button>
          <el-button
              type="primary"
              plain
              @click="divisionMode = 'manual'"
              :class="divisionMode === 'manual' ? 'selected-mode' : ''"
              size="large"
          >
            手动分班
          </el-button>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="flex justify-end gap-2 mt-4">
        <el-button type="primary" plain @click="resetRules" size="small">重置规则</el-button>
        <el-button type="primary" @click="submitClassDivision" size="small" :loading="isSubmitting">生成班级</el-button>
      </div>
    </div>

    <!-- 分班结果模块 -->
    <div class="header mt-6">
      <h2 class="text-xl font-semibold">分班结果</h2>
      <div v-if="modifiedClassIds.size > 0" class="text-orange-500 text-sm mt-1 flex items-center">
        <el-icon size="14" class="mr-1"><Warning /></el-icon>
        有 {{ modifiedClassIds.size }} 个班级有新增学生，请提交
      </div>
    </div>
    <el-card class="mb-6 rounded-lg shadow-md">
      <div class="p-4 space-y-4">
        <!-- 统计信息 -->
        <el-row :gutter="24" class="mb-4">
          <el-col :span="8">
            <div class="stat-card">
              <p class="text-sm text-gray-500">总学生数</p>
              <h3 class="text-xl font-bold">{{ totalStudents }}人</h3>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-card">
              <p class="text-sm text-gray-500">生成班级数</p>
              <h3 class="text-xl font-bold">{{ classCount }}个班级</h3>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-card">
              <p class="text-sm text-gray-500">平均班级人数</p>
              <h3 class="text-xl font-bold">{{ averageStudents }}人</h3>
            </div>
          </el-col>
        </el-row>

        <!-- 班级列表 -->
        <el-table :data="classResults" border style="width: 100%" @row-click="handleTableRowClick">
          <el-table-column label="班级名称" align="center">
            <template #default="scope">
              <div class="flex items-center justify-center">
                {{ scope.row.classInfo.className }}
                <el-tag v-if="isClassModified(scope.row)" size="mini" type="warning" class="ml-2">
                  有新增
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="学年" align="center">
            <template #default="scope">
              {{ getAcademicYearLabel(scope.row.classInfo.academicYear) }}
            </template>
          </el-table-column>
          <el-table-column label="学生人数" align="center">
            <template #default="scope">{{ scope.row.students?.length || 0 }} / {{ scope.row.maxSize || formData.maxClassSize }}</template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button
                  type="link"
                  icon="el-icon-plus"
                  size="mini"
                  @click="handleAddStudents(scope.row)"
                  :disabled="!scope.row.maxSize && !formData.maxClassSize"
                  :loading="isSubmitting"
              >
                添加学生
              </el-button>
              <el-button
                  type="link"
                  icon="el-icon-view"
                  size="small"
                  @click="handleViewDetails(scope.row)"
                  :loading="isSubmitting"
              >
                查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 操作按钮 -->
        <div class="flex justify-end gap-2 mt-4">
          <el-button
              type="primary"
              size="small"
              v-if="modifiedClassIds.size > 0"
              @click="submitModifiedClasses"
              :loading="isSubmitting"
          >
            提交修改
          </el-button>
          <el-button
              type="primary"
              size="small"
              v-if="divisionMode === 'manual' && classResults.length > 0"
              @click="submitManualClassDivision"
              :loading="isSubmitting"
          >
            提交分班结果
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 添加学生弹窗 -->
    <el-dialog
        title="添加学生到班级"
        v-model="showAddStudentDialog"
        width="70%"
        :close-on-click-modal="false"
        :before-close="handleAddDialogClose"
    >
      <div class="mb-4">
        <p class="font-medium">当前班级: {{ currentClass?.classInfo?.className || '未选择班级' }}</p>
        <p class="text-gray-500">已选人数: {{ currentClass?.students?.length || 0 }} / {{ currentClass?.maxSize || formData.maxClassSize || 0 }}</p>
        <p class="text-xs text-orange-500 mt-1">提示：仅显示未分配到任何班级的学生</p>
      </div>

      <el-table
          :data="availableStudents"
          style="width: 100%;"
          border
          @selection-change="handleSelectionChange"
          ref="studentTableRef"
          :loading="availableStudentsLoading"
          row-key="id"
      >
        <el-table-column type="selection" width="55" :selectable="isSelectable" />
        <el-table-column label="学号" align="center" prop="studentId" width="160" />
        <el-table-column label="学生姓名" align="center" prop="studentName" width="120" />
        <el-table-column label="学院名称" align="center" prop="collegeName" />
        <el-table-column label="专业名称" align="center" prop="majorName" />
        <el-table-column label="培养方案" align="center" prop="trainingProgramName" />
      </el-table>

      <template #footer>
        <el-button @click="showAddStudentDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmAddStudents" :loading="isSubmitting">确认添加</el-button>
      </template>
    </el-dialog>

    <!-- 培养方案学生名单弹窗 -->
    <el-dialog
        title="培养方案学生名单"
        v-model="showProgramStudentDialog"
        width="70%"
        :close-on-click-modal="false"
    >
      <el-table :data="programStudents" style="width: 100%;" border row-key="studentId">
        <el-table-column label="学号" align="center" prop="studentId" />
        <el-table-column label="学生姓名" align="center" prop="studentName" />
        <el-table-column label="培养方案名称" align="center" prop="trainingProgramName" />
        <el-table-column label="学院名称" align="center" prop="collegeName" />
        <el-table-column label="专业名称" align="center" prop="majorName" />
      </el-table>
    </el-dialog>

    <!-- 班级学生详情弹窗 -->
    <el-dialog
        title="班级学生名单"
        v-model="showStudentDialog"
        width="70%"
        :close-on-click-modal="false"
    >
      <el-table :data="currentClassStudents" style="width: 100%;" border row-key="studentId">
        <el-table-column label="学号" align="center" prop="studentId" />
        <el-table-column label="学生姓名" align="center" prop="studentName" />
        <el-table-column label="学院名称" align="center" prop="collegeName" />
        <el-table-column label="专业名称" align="center" prop="majorName" />
        <el-table-column label="操作" align="center" width="100">
          <template #default="scope">
            <el-button
                type="link"
                icon="el-icon-delete"
                size="mini"
                text-color="red"
                @click="handleRemoveFromClass(scope.row)"
                :disabled="isSubmitting"
            >
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, onMounted, computed, watch, getCurrentInstance, toRaw, nextTick} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import {listCollege} from "@/api/college/college";
import {listTrainingManagement, getTrainingManagement} from "@/api/trainingManagement/trainingManagement";
import {getCourse} from "@/api/course/course";
import {getCurrentYearAndTerm } from "@/api/course/term";
import {
  School, Calendar, Clock, Document, Menu, ChatLineSquare,
  User, Tools, UserFilled, Warning
} from '@element-plus/icons-vue';
import {generateClassList, saveManualClassDivision,updateStatusById} from "@/api/trainingManagement/programPourses";
import {
  listStudentManger,
  getCourseScheduleWithStudents,
  selectStudentInfoListByTrainingProgramIds
} from "@/api/student/studentManger";
import {ElMessageBox} from 'element-plus';
import {getSubjectIdListByProgramId} from "@/api/college/researchDirection";
import {updateCourseStudentInfoList} from "@/api/trainingManagement/CourseStudentInfo";

// ---------------------- 基础数据存储 ----------------------
const filteredTrainingManagementList = ref([]);
const programSubjectMap = ref(new Map()); // 培养方案-学科映射
const subjectLoadingMap = ref(new Map()); // 学科加载状态
const route = useRoute();
const courseId = ref(''); // 课程ID
const selectedGrade = ref(''); // 选中年级
const selectedSemester = ref(''); // 选中学期
const trainingProgramIds = ref([]); // 培养方案ID列表
const status = ref(''); // 分班状态（0未分班/1已分班）
const courseCharacter = ref(''); // 课程性质
const isSubmitting = ref(false); // 提交中状态
const tableData = ref([]); // 课程信息
const collegeList = ref([]); // 学院列表
const trainingPrograms = ref([]); // 培养方案列表
const studentInfoMap = ref(new Map()); // 学号-姓名映射
const collegeLoaded = ref(false); // 学院数据加载状态
const divisionMode = ref('auto'); // 分班方式（auto/manual）
const showStudentDialog = ref(false); // 班级详情弹窗
const currentClassStudents = ref([]); // 当前班级学生
const allProgramStudents = ref({}); // 所有培养方案学生（按方案ID分组）
const studentTableRef = ref(null); // 学生选择表格引用
const currentSelectedStudents = ref([]); // 当前选中待添加学生
const manualClasses = ref([]); // 手动分班班级列表
const showAddStudentDialog = ref(false); // 添加学生弹窗
const currentClass = ref(null); // 当前操作班级
const availableStudents = ref([]); // 可添加学生列表（未分配学生池）
const availableStudentsLoading = ref(false); // 可添加学生加载状态
const router = useRouter();
// 存储当前学年信息（从接口获取）
const currentAcademicYear = ref('');
// ---------------------- 班级修改状态跟踪 ----------------------
const modifiedClassIds = ref(new Set()); // 有新增学生的班级ID集合（去重）
const addedStudentsMap = ref(new Map()); // 记录每个班级新增的学生：key=班级ID，value=学生ID数组

// ---------------------- 分班结果计算 ----------------------
const autoClassResults = ref([]); // 自动分班结果
const classResults = computed(() => {
  // 手动分班优先：若手动分班列表有数据且模式为手动，显示手动结果
  if (divisionMode.value === 'manual' && manualClasses.value.length > 0) {
    return manualClasses.value;
  }
  // 否则显示自动分班结果
  return autoClassResults.value;
});

// ---------------------- 字典数据（项目原有封装） ----------------------
const {proxy} = getCurrentInstance();
const {semester, grade, characteristics_of_the_course, academic_year, culture_program_type} = proxy.useDict(
    'semester', "grade", 'characteristics_of_the_course', 'academic_year', 'culture_program_type'
);

// ---------------------- 弹窗相关 ----------------------
const showProgramStudentDialog = ref(false); // 培养方案学生弹窗
const programStudents = ref([]); // 培养方案学生列表

// ---------------------- 表单数据（初始化明确为空字符串，避免undefined） ----------------------
const formData = ref({
  maxClassSize: '', // 最大班级人数
  numClasses: '', // 开班数量
  classDivisionStrategy: [], // 分班策略（预留）
  enableGradeBasedClass: false, // 按年级分班（预留）
});

const trainingProgramCoursesIds = ref([]);

// ---------------------- 基础工具方法 ----------------------
/** 重置分班规则 */
const resetRules = () => {
  formData.value.maxClassSize = '';
  formData.value.numClasses = '';
  divisionMode.value = 'auto';
  autoClassResults.value = [];
  manualClasses.value = [];
  modifiedClassIds.value.clear();
  addedStudentsMap.value.clear();
  proxy.$modal.msgSuccess('分班规则已重置');
};

/** 分班状态判断（已分班/未分班） */
const isStatusActive = computed(() => {
  // 状态为1（已分班）或3（完成排课任务）时都不显示分班规则设置
  const statusNum = Number(status.value);
  return statusNum === 1 || statusNum === 3;
});

/** 获取路由参数并初始化 */
const getQueryParams = () => {
  const {
    courseId: id, grade: g, semester: s, trainingProgramIds: ids,
    status: st, courseCharacter: cc,trainingProgramCoursesIds: Coursesids
  } = route.query;

  courseId.value = id || '';
  selectedGrade.value = g || '';
  selectedSemester.value = s || '';
  status.value = st || '0'; // 默认未分班
  courseCharacter.value = cc || '';

  // 处理培养方案ID（去重+过滤空值）
  trainingProgramIds.value = ids
      ? [...new Set(ids.split(',').filter(id => id.trim()))]
      : [];
  trainingProgramCoursesIds.value = Coursesids
      ? [...new Set(Coursesids.split(',').filter(id => id.trim()))]
      : [];
};

/** 获取培养方案对应的学科信息 */
const fetchProgramSubjectInfo = async (programId) => {
  if (programSubjectMap.value.has(programId) || subjectLoadingMap.value.get(programId)) return;
  subjectLoadingMap.value.set(programId, true);
  try {
    const response = await getSubjectIdListByProgramId(programId);
    programSubjectMap.value.set(
        programId,
        response.code === 200 && Array.isArray(response.data) ? response.data : []
    );
  } catch (error) {
    programSubjectMap.value.set(programId, []);
    proxy.$modal.msgError(`培养方案[${programId}]学科信息加载失败`);
  } finally {
    subjectLoadingMap.value.set(programId, false);
  }
};

/** 获取课程性质标签 */
const getCourseCharacterLabel = () => {
  if (!courseCharacter.value) return '未知类型';
  const item = characteristics_of_the_course.value.find(
      dict => String(dict.value) === String(courseCharacter.value)
  );
  return item ? item.label : `未知类型(${courseCharacter.value})`;
};

/** 获取学年标签 */
const getAcademicYearLabel = (value) => {
  if (value === undefined || value === null || value === '') return '未知学年';
  const targetValue = String(value);
  const item = academic_year.value.find(dict => String(dict.value) === targetValue);
  return item ? item.label : `未知(${value})`;
};

// 新增：判断是否为临时班学生
const isTempClassStudent = (student) => {
  // 假设临时班ID以'TEMP_'开头，可根据实际业务调整
  return student.courseScheduleDetailsId?.startsWith('TEMP_') || false;
};

// 4. 在页面初始化加载学生数据时，为已有学生初始化原始ID字段
const initStudentOriginalId = (students) => {
  return students.map(student => {
    // 如果是临时班学生且未初始化原始ID
    if (isTempClassStudent(student) && !student.originalCourseScheduleDetailsId) {
      return {
        ...student,
        // 初始化原始ID（从current字段或其他可能存储的地方）
        originalCourseScheduleDetailsId: student.currentCourseScheduleDetailsId || null
      };
    }
    // 非临时班学生，原始ID就是当前课程ID
    if (!student.originalCourseScheduleDetailsId) {
      return {
        ...student,
        originalCourseScheduleDetailsId: student.courseScheduleDetailsId || null
      };
    }
    return student;
  });
};

// ---------------------- 班级修改状态管理 ----------------------
/** 初始化班级新增学生记录 */
const initAddedStudentsMap = (classList) => {
  modifiedClassIds.value.clear();
  addedStudentsMap.value.clear();

  classList.forEach(classItem => {
    const classKey = classItem.classInfo.id;
    if (!classKey) return;

    // 初始状态没有新增学生
    addedStudentsMap.value.set(classKey, []);
  });
};

/** 标记班级有新增学生 */
const markClassAsModified = (classId, newStudentIds) => {
  if (!classId || !newStudentIds || newStudentIds.length === 0) return;

  // 获取当前班级已记录的新增学生
  const existingAdded = addedStudentsMap.value.get(classId) || [];

  // 添加新的学生ID（去重）
  const allAdded = [...new Set([...existingAdded, ...newStudentIds])];

  // 更新记录
  addedStudentsMap.value.set(classId, allAdded);

  // 如果有新增学生，标记班级为修改
  if (allAdded.length > 0) {
    modifiedClassIds.value.add(classId);
  } else {
    modifiedClassIds.value.delete(classId);
  }
};

/** 移除学生时更新新增记录 */
const updateAddedStudentsOnRemove = (classId, studentId) => {
  if (!classId || !studentId) return;

  // 获取当前班级已记录的新增学生
  const existingAdded = addedStudentsMap.value.get(classId) || [];

  // 过滤掉被移除的学生
  const remainingAdded = existingAdded.filter(id => id !== studentId);

  // 更新记录
  addedStudentsMap.value.set(classId, remainingAdded);

  // 如果没有新增学生了，移除标记
  if (remainingAdded.length === 0) {
    modifiedClassIds.value.delete(classId);
  }
};

/** 判断班级是否有新增学生 */
const isClassModified = (classItem) => {
  const classKey = classItem.classInfo.id;
  const addedStudents = addedStudentsMap.value.get(classKey) || [];
  return addedStudents.length > 0;
};

// ---------------------- 学生选择与班级调整 ----------------------
/** 学生选择变化处理（限制班级容量） */
const handleSelectionChange = (selection) => {
  if (!currentClass.value) return;

  // 计算剩余容量
  const maxSize = currentClass.value.maxSize || parseInt(formData.value.maxClassSize) || 0;
  const existingCount = currentClass.value.students.length;
  const remaining = maxSize - existingCount;

  // 过滤已在其他班级的学生（双重保险）
  const validSelection = selection.filter(row => !isStudentInAnyClass(row.studentId));

  // 限制选择数量不超过剩余容量
  if (validSelection.length > remaining) {
    const limitedSelection = validSelection.slice(0, remaining);
    currentSelectedStudents.value = limitedSelection;

    // 同步表格选中状态
    nextTick(() => {
      studentTableRef.value?.clearSelection();
      limitedSelection.forEach(student => {
        studentTableRef.value?.toggleRowSelection(student, true);
      });
    });

    proxy.$modal.msgWarning(`班级最大容量为${maxSize}人，已自动保留前${remaining}名学生`);
  } else {
    currentSelectedStudents.value = validSelection;
  }
};

/** 判断学生是否可选择（未在任何班级） */
const isSelectable = (row) => {
  return !isStudentInAnyClass(row.studentId);
};

/** 判断学生是否已在任何班级（用学号判断，避免主键ID问题） */
const isStudentInAnyClass = (studentId) => {
  // 遍历所有班级检查
  for (const cls of [...manualClasses.value, ...autoClassResults.value]) {
    if (cls.students.some(s => String(s.studentId) === String(studentId))) {
      return true;
    }
  }
  return false;
};


/** 移除学生（修复：确保含临时班字段的学生同步到数据源，避免字段丢失） */
const handleRemoveFromClass = (student) => {
  ElMessageBox.confirm(
      `确定要将【${student.studentName}（${student.studentId}）】从当前班级移除吗？`,
      '确认移除',
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
  ).then(async () => {
    if (!currentClass.value) return;

    const studentId = student.studentId;
    const currentClassId = currentClass.value.classInfo.id;

    // 1. 保留原始班级ID（直接使用学生已有字段，不额外赋值）
    const finalOriginalClassId = student.currentCourseScheduleDetailsId || currentClassId;
    // 构建含完整临时班字段的移除学生数据
    const removedStudent = {
      ...student,
      currentCourseScheduleDetailsId: finalOriginalClassId, // 原始班ID（不修改）
      originalCourseScheduleDetailsId: student.originalCourseScheduleDetailsId || finalOriginalClassId, // 双重保障
      courseScheduleDetailsId: null // 移除后无目标班级
    };
    console.log('移除后学生完整数据（含临时班字段）：', removedStudent);

    // 2. 从当前班级移除学生
    currentClass.value.students = currentClass.value.students.filter(
        s => String(s.studentId) !== String(studentId)
    );

    // 3. 更新新增记录
    updateAddedStudentsOnRemove(currentClassId, studentId);

    // 4. 更新班级列表（深拷贝避免引用污染）
    const updatedClass = JSON.parse(JSON.stringify(currentClass.value));
    if (divisionMode.value === 'manual') {
      const classIndex = manualClasses.value.findIndex(
          cls => cls.classInfo.id === currentClassId
      );
      if (classIndex !== -1) manualClasses.value[classIndex] = updatedClass;
    } else {
      const classIndex = autoClassResults.value.findIndex(
          cls => cls.classInfo.id === currentClassId
      );
      if (classIndex !== -1) autoClassResults.value[classIndex] = updatedClass;
    }

    // 5. 关键修复：强制同步含临时班字段的学生到数据源（无论培养方案ID是否存在）
    if (student.trainingProgramId) {
      // 有培养方案ID：同步到对应方案的数据源
      const programKey = student.trainingProgramId;
      if (!allProgramStudents.value[programKey]) {
        allProgramStudents.value[programKey] = [];
      }
      // 替换数据源中该学生的旧数据（确保用含临时班字段的新数据）
      const programStudents = allProgramStudents.value[programKey];
      const studentIndex = programStudents.findIndex(s => s.studentId === studentId);
      if (studentIndex !== -1) {
        programStudents[studentIndex] = removedStudent;
        allProgramStudents.value[programKey] = programStudents;
        console.log(`已同步学生[${studentId}]到数据源（培养方案ID: ${programKey}）`);
      } else {
        // 数据源中无该学生：直接添加
        programStudents.push(removedStudent);
        allProgramStudents.value[programKey] = programStudents;
        console.log(`已新增学生[${studentId}]到数据源（培养方案ID: ${programKey}）`);
      }
    } else {
      // 无培养方案ID：临时存储到“默认”分组，避免丢失
      if (!allProgramStudents.value['DEFAULT']) {
        allProgramStudents.value['DEFAULT'] = [];
      }
      const defaultStudents = allProgramStudents.value['DEFAULT'];
      const studentIndex = defaultStudents.findIndex(s => s.studentId === studentId);
      if (studentIndex !== -1) {
        defaultStudents[studentIndex] = removedStudent;
      } else {
        defaultStudents.push(removedStudent);
      }
      allProgramStudents.value['DEFAULT'] = defaultStudents;
      console.log(`已同步学生[${studentId}]到默认数据源（无培养方案ID）`);
    }

    // 6. 刷新弹窗和可添加学生列表
    if (showStudentDialog.value) {
      currentClassStudents.value = [...currentClass.value.students];
    }
    await collectAvailableStudents();

    proxy.$modal.msgSuccess(`已将【${student.studentName}】从班级移除`);
  }).catch(() => { /* 取消移除不处理 */ });
};

/** 获取学院名称（带编码） */
const getCollegeName = (collegeId, loaded) => {
  if (!loaded) return '加载中...';
  if (!collegeId) return '未知学院';

  const targetId = String(collegeId).trim();
  const college = collegeList.value.find(
      c => String(c.collegeId).trim() === targetId
  );

  return college ? `${college.collegeName}（${college.collegeCode || '无编码'}）` : '未知学院';
};

// ---------------------- 添加学生弹窗逻辑 ----------------------
/** 打开添加学生弹窗 */
const handleAddStudents = async (classData) => {
  try {
    // 深拷贝班级数据，避免修改原始数据
    currentClass.value = JSON.parse(JSON.stringify(toRaw(classData)));
    currentSelectedStudents.value = [];
    showAddStudentDialog.value = true;

    // 加载可添加学生列表（未分配学生池）
    await collectAvailableStudents();
  } catch (error) {
    console.error('【添加学生】打开弹窗失败:', error);
    proxy.$modal.msgError('打开添加学生弹窗失败，请重试');
  }
};

/** 关闭添加学生弹窗时清除选中 */
const handleAddDialogClose = () => {
  currentSelectedStudents.value = [];
  nextTick(() => {
    studentTableRef.value?.clearSelection();
  });
};

/** 确认添加学生到班级 - 移除多余的 UNKNOWN_ORIGIN 兜底，直接使用已有正确字段 */
const confirmAddStudents = async () => {
  if (!currentClass.value) {
    proxy.$modal.msgWarning('未选择目标班级');
    return;
  }

  if (currentSelectedStudents.value.length === 0) {
    proxy.$modal.msgWarning('请先选择要添加的学生');
    return;
  }

  // 再次校验班级容量
  const maxSize = currentClass.value.maxSize || parseInt(formData.value.maxClassSize) || 0;
  const existingCount = currentClass.value.students.length;
  const addCount = currentSelectedStudents.value.length;
  const newCount = existingCount + addCount;

  if (newCount > maxSize) {
    proxy.$modal.msgError(`班级最大容量为${maxSize}人，当前已选${existingCount}人，最多可再添加${maxSize - existingCount}人`);
    return;
  }

  try {
    isSubmitting.value = true;

    // 获取当前操作的目标班级ID
    const targetClassId = currentClass.value.classInfo.id;

    // 获取新增学生的ID列表
    const newStudentIds = currentSelectedStudents.value.map(s => s.studentId);

    // 构建添加学生数据（核心修改：直接使用已有正确的原始班级ID字段，无需 UNKNOWN_ORIGIN 兜底）
    const studentsToAdd = currentSelectedStudents.value.map(student => {
      // 直接使用 student.originalCourseScheduleDetailsId 或 student.currentCourseScheduleDetailsId（已有正确值）
      const originalId = student.originalCourseScheduleDetailsId
          || student.currentCourseScheduleDetailsId; // 移除 || 'UNKNOWN_ORIGIN'，无需兜底

      return {
        ...student,
        // 新班级ID（目标班级的ID）
        courseScheduleDetailsId: targetClassId,
        // 永久保留进入临时班前的原始班级ID（已有正确值，无需修改）
        currentCourseScheduleDetailsId: originalId,
        // 保留原始ID的备份字段，防止后续操作丢失（双重保障）
        originalCourseScheduleDetailsId: originalId
      };
    });

    // 打印验证：确认添加到新班的学生包含正确的原始班级ID
    console.log('添加到新班的学生数据（含正确原始班级ID）：', studentsToAdd);

    // 添加学生到当前班级
    currentClass.value.students.push(...studentsToAdd);

    // 标记班级有新增学生
    markClassAsModified(targetClassId, newStudentIds);

    // 更新班级列表（深拷贝避免引用问题）
    const updatedClass = JSON.parse(JSON.stringify(currentClass.value));
    if (divisionMode.value === 'manual') {
      const classIndex = manualClasses.value.findIndex(
          cls => cls.classInfo.id === targetClassId
      );
      if (classIndex !== -1) manualClasses.value[classIndex] = updatedClass;
    } else {
      const classIndex = autoClassResults.value.findIndex(
          cls => cls.classInfo.id === targetClassId
      );
      if (classIndex !== -1) autoClassResults.value[classIndex] = updatedClass;
    }

    // 刷新可添加学生列表（移除已添加的学生）
    await collectAvailableStudents();

    // 清除选中状态
    currentSelectedStudents.value = [];
    nextTick(() => {
      studentTableRef.value?.clearSelection();
    });

    proxy.$modal.msgSuccess(`成功添加${addCount}名学生到班级`);
  } catch (error) {
    console.error('【添加学生】失败:', error);
    proxy.$modal.msgError('添加学生失败，请重试');
  } finally {
    isSubmitting.value = false;
  }
};
// 修改状态更新方法，修复URL参数错误
const updateTrainingProgramsStatus = async () => {
  if (trainingProgramCoursesIds.value.length === 0) return;

  const successIds = [];
  const failIds = [];

  try {
    for (const id of trainingProgramCoursesIds.value) {
      try {
        console.log(`开始更新ID: ${id} 的状态`);
        const response = await updateStatusById(id, 3);

        console.log(`ID: ${id} 的完整响应:`, {
          status: response.status,
          statusText: response.statusText,
          data: response.data,
          headers: response.headers
        });

        const isSuccess =
            (response.status >= 200 && response.status < 300) &&
            (response.data?.code === 0 ||
                response.data?.success === true ||
                response.data?.code === 200 ||
                response.data === undefined);

        if (isSuccess) {
          successIds.push(id);
          console.log(`ID: ${id} 更新成功`);
        } else {
          failIds.push({
            id,
            reason: response.data?.message || `响应异常: ${JSON.stringify(response.data)}`
          });
          console.warn(`ID: ${id} 更新失败，响应不满足成功条件`);
        }
      } catch (error) {
        console.error(`ID: ${id} 调用接口异常:`, {
          message: error.message,
          response: error.response?.data,
          status: error.response?.status
        });
        failIds.push({
          id,
          reason: error.response?.data?.message || error.message || '接口调用异常'
        });
      }
    }

    // 移除所有提示信息，只在控制台保留日志
    console.log(`成功更新 ${successIds.length}/${trainingProgramCoursesIds.value.length} 个培养方案课程状态`);
    if (failIds.length > 0) {
      console.warn('培养方案课程状态更新失败详情:', failIds);
    }

    if (successIds.length > 0) {
      status.value = '1';
    }
  } catch (error) {
    console.error('批量更新培养方案课程状态失败:', error);
  }
};
/** 收集可添加学生（未分配学生池） */
/** 收集可添加学生（修复：优先保留含临时班字段的学生数据，确保字段不丢失） */
const collectAvailableStudents = async () => {
  availableStudentsLoading.value = true;
  try {
    // 1. 从所有班级中获取已分配/已移除的学生（含完整临时班字段，优先级最高）
    const assignedStudents = [];
    [...manualClasses.value, ...autoClassResults.value].forEach(classItem => {
      if (Array.isArray(classItem.students)) {
        // 打印验证：确认班级学生包含临时班字段
        console.log('班级学生数据（含临时班字段）：', classItem.students[0] || '无学生');
        assignedStudents.push(...classItem.students);
      }
    });

    // 2. 从同步后的数据源获取学生（含已同步的临时班字段）
    const programStudentsList = [];
    Object.values(allProgramStudents.value).forEach(students => {
      if (Array.isArray(students)) {
        // 打印验证：确认数据源学生是否包含临时班字段
        console.log('数据源学生数据（同步后）：', students[0] || '无学生');
        programStudentsList.push(...students);
      }
    });

    // 3. 合并数据：已分配学生（含临时班字段）优先级 > 数据源学生（避免初始数据覆盖）
    const allPossibleStudents = [...assignedStudents, ...programStudentsList];

    // 4. 去重（按学号）：确保同一学生保留含临时班字段的最新数据
    const uniqueStudentsMap = new Map();
    allPossibleStudents.forEach(student => {
      if (student.studentId) {
        // 关键：如果已有该学生，仅当新数据含临时班字段时才更新（避免覆盖）
        const existingStudent = uniqueStudentsMap.get(student.studentId);
        if (!existingStudent ||
            (student.currentCourseScheduleDetailsId || student.originalCourseScheduleDetailsId)) {
          uniqueStudentsMap.set(student.studentId, student);
        }
      }
    });
    const allStudents = Array.from(uniqueStudentsMap.values());

    // 5. 筛选未分配学生（未在任何班级中）
    const unassignedStudents = allStudents.filter(student => {
      const isUnassigned = !isStudentInAnyClass(student.studentId);
      // 打印验证：未分配学生是否包含临时班字段
      if (isUnassigned) {
        console.log(`未分配学生[${student.studentId}]字段：`, {
          currentCourseScheduleDetailsId: student.currentCourseScheduleDetailsId,
          originalCourseScheduleDetailsId: student.originalCourseScheduleDetailsId
        });
      }
      return isUnassigned;
    });

    // 最终可添加学生列表（确保含临时班字段）
    availableStudents.value = unassignedStudents;
    console.log('可添加学生池最终数据（含临时班字段）：', availableStudents.value);

  } catch (error) {
    console.error('【收集可添加学生】失败:', error);
    availableStudents.value = [];
    proxy.$modal.msgWarning('加载可添加学生列表失败');
  } finally {
    availableStudentsLoading.value = false;
  }
};
// ---------------------- 分班核心逻辑 ----------------------
/** 提交分班规则（自动/手动） */
const submitClassDivision = async () => {
  if (isStatusActive.value) {
    proxy.$modal.msgWarning('已分班状态下不允许重新生成班级');
    return;
  }

  // 参数校验
  const maxSizeStr = formData.value.maxClassSize.trim();
  const numClsStr = formData.value.numClasses.trim();
  const maxSize = Number(maxSizeStr);
  const numCls = Number(numClsStr);

  // 步骤1：判断是否为空
  if (!maxSizeStr || !numClsStr) {
    proxy.$modal.msgError('请填写最大班级人数和开班数量');
    return;
  }

  // 步骤2：判断是否为有效数字
  if (isNaN(maxSize) || isNaN(numCls)) {
    proxy.$modal.msgError('最大班级人数和开班数量数量必须为数字');
    return;
  }

  // 步骤3：判断是否大于0
  if (maxSize <= 0 || numCls <= 0) {
    proxy.$modal.msgError('最大班级人数和开班数量必须大于0');
    return;
  }

  // 手动分班：生成空班级 - 不更新状态
  if (divisionMode.value === 'manual') {
    await generateManualClasses();
    return;
  }

  // 自动分班：调用接口生成班级
  try {
    isSubmitting.value = true;

    // 构建自动分班参数
    const autoDivisionParams = {
      courseId: courseId.value.trim(),
      courseInfo: {
        ...tableData.value[0],
        isRequired: tableData.value[0]?.isRequired !== undefined
            ? Number(tableData.value[0].isRequired)
            : 0,
        departmentId: tableData.value[0]?.departmentId || tableData.value[0]?.departmentName || '未知学院',
        courseName: tableData.value[0]?.courseName || '未知课程',
        courseCode: tableData.value[0]?.courseCode || '未知编号'
      },
      trainingProgramIds: trainingProgramIds.value.filter(id => id.trim()),
      trainingPrograms: filteredTrainingManagementList.value.map(program => ({
        ...program,
        amount: program.amount ? Number(program.amount) : 0,
        grade: program.grade ? Number(program.grade) : 0
      })),
      grade: selectedGrade.value ? Number(selectedGrade.value) : 0,
      semester: selectedSemester.value ? Number(selectedSemester.value) : 0,
      academicYear: currentAcademicYear.value ? Number(currentAcademicYear.value) : 0,
      divisionRules: {
        maxClassSize: maxSize,
        numClasses: numCls
      }
    };

    const response = await generateClassList(autoDivisionParams);

    if (response.code === 200 && Array.isArray(response.data)) {
      // 自动分班学生数据处理
      autoClassResults.value = response.data.map(cls => ({
        ...cls,
        maxSize: maxSize,
        students: initStudentOriginalId(
            (cls.students || []).map(student => ({
              ...student,
              courseScheduleDetailsId: cls.classInfo.id,
              currentCourseScheduleDetailsId: null
            }))
        )
      }));

      // 初始化新增学生记录
      initAddedStudentsMap(autoClassResults.value);

      // 构建学号-姓名映射
      const studentIds = new Set();
      autoClassResults.value.forEach(classItem => {
        classItem.students.forEach(student => {
          studentIds.add(student.studentId);
          studentInfoMap.value.set(student.studentId, student.studentName);
        });
      });

      proxy.$modal.msgSuccess('自动分班成功，可查看结果');

      // 自动分班时更新状态
      if (trainingProgramCoursesIds.value.length > 0) {
        await updateTrainingProgramsStatus();
      }
    } else {
      proxy.$modal.msgError(response.message || '自动分班失败');
    }
  } catch (error) {
    console.error('【自动分班】接口异常:', error);
    proxy.$modal.msgError('调用接口失败，请稍后重试');
  } finally {
    isSubmitting.value = false;
  }
};

/** 生成手动分班的空班级 */
const generateManualClasses = async () => {
  try {
    // 使用校验后的数字
    const numClasses = Number(formData.value.numClasses.trim());
    const maxSize = Number(formData.value.maxClassSize.trim());
    const courseName = tableData.value[0]?.courseName || '未知课程';
    const semesterItem = semester.value.find(
        item => String(item.value) === String(selectedSemester.value)
    );
    const semesterLabel = semesterItem ? semesterItem.label : selectedSemester.value;
    const grade = selectedGrade.value ? Number(selectedGrade.value) : 0;
    const academicYear = 0;

    // 生成空班级列表
    manualClasses.value = Array.from({length: numClasses}, (_, i) => ({
      classInfo: {
        className: `${courseName}-${semesterLabel}-${i + 1}班`,
        academicYear: academicYear,
        semester: selectedSemester.value ? Number(selectedSemester.value) : 0,
        grade: grade,
        courseId: courseId.value.trim(),
        department: tableData.value[0]?.departmentId || tableData.value[0]?.departmentName || '未知学院',
        maxCapacity: maxSize,
        id: `MANUAL_${courseId.value}_${Date.now()}_${i + 1}` // 临时ID
      },
      students: [], // 空学生列表
      maxSize: maxSize
    }));

    // 初始化新增学生记录
    initAddedStudentsMap(manualClasses.value);

    // 加载培养方案学生（用于手动添加）
    if (trainingProgramIds.value.length > 0) {
      await fetchProgramStudents();
    }

    proxy.$modal.msgSuccess(`手动分班预览生成成功，已创建${numClasses}个空班级`);
  } catch (error) {
    console.error('【生成手动班级】失败:', error);
    proxy.$modal.msgError('生成手动班级失败，请重试');
  }
};

/** 提交手动分班结果 */
const submitManualClassDivision = async () => {
  // 前置校验
  if (!courseId.value) {
    proxy.$modal.msgError('未获取到课程ID，请刷新页面重试');
    return;
  }

  if (!tableData.value || !tableData.value.length) {
    proxy.$modal.msgError('未获取到课程信息，请先加载课程');
    return;
  }

  if (trainingProgramIds.value.length === 0) {
    proxy.$modal.msgError('未获取到培养方案ID，无法提交');
    return;
  }

  if (manualClasses.value.length === 0) {
    proxy.$modal.msgWarning('请先生成手动分班班级');
    return;
  }

  // 校验空班级
  const emptyClasses = manualClasses.value.filter(cls => cls.students.length === 0);
  if (emptyClasses.length > 0) {
    proxy.$modal.msgWarning(`存在${emptyClasses.length}个空班级，请为所有班级添加学生后提交`);
    return;
  }

  // 校验学生主键ID
  const invalidClasses = [];
  manualClasses.value.forEach(cls => {
    const missingIdStudents = cls.students.filter(s => !s.id && s.id !== 0);
    if (missingIdStudents.length > 0) {
      invalidClasses.push({
        className: cls.classInfo.className,
        count: missingIdStudents.length
      });
    }
  });

  if (invalidClasses.length > 0) {
    const msg = invalidClasses.map(item =>
        `班级【${item.className}】存在${item.count}个缺少主键ID的学生`
    ).join('；');
    proxy.$modal.msgError(`提交失败：${msg}，请重新加载学生数据`);
    return;
  }

  try {
    isSubmitting.value = true;

    // 构建手动分班提交参数
    const courseDepartment = tableData.value[0]?.departmentId || tableData.value[0]?.departmentName || '未知学院';
    const baseGrade = selectedGrade.value ? Number(selectedGrade.value) : 0;
    const baseSemester = selectedSemester.value ? Number(selectedSemester.value) : 0;
    const baseTrainingProgramId = trainingProgramIds.value[0]?.trim() || '';

    const submitData = {
      classes: manualClasses.value.map(classItem => ({
        trainingProgramCoursesId: route.query.trainingProgramCoursesIds?.trim() || `TEMP_${Date.now()}`,
        courseId: courseId.value.trim(),
        trainingProgramId: baseTrainingProgramId,
        semester: baseSemester,
        academicYear: currentAcademicYear.value ? Number(currentAcademicYear.value) : 0,
        grade: baseGrade,
        className: classItem.classInfo.className,
        maxCapacity: classItem.maxSize ? Number(classItem.maxSize) : 50,
        isRequired: tableData.value[0]?.isRequired !== undefined
            ? Number(tableData.value[0].isRequired)
            : 0,
        department: courseDepartment,
        // 传递学生主键ID列表
        studentIds: classItem.students.map(student => String(student.id)).filter(id => id)
      })),
      trainingPrograms: trainingProgramIds.value
          .filter(id => id.trim())
          .map(programId => ({id: programId.trim()}))
    };

    const response = await saveManualClassDivision(submitData);

    if (response.code === 200 && Array.isArray(response.data)) {
      // 处理后端返回的班级数据
      manualClasses.value = response.data.map(cls => ({
        classInfo: cls.classInfo || {},
        students: initStudentOriginalId(
            (cls.students || []).map(student => ({
              ...student,
              courseScheduleDetailsId: cls.classInfo.id,
              currentCourseScheduleDetailsId: null
            }))
        ),
        maxSize: cls.classInfo?.maxCapacity || formData.value.maxClassSize
      }));

      // 重新初始化新增学生记录
      initAddedStudentsMap(manualClasses.value);

      proxy.$modal.msgSuccess('手动分班提交成功！');

      // 手动分班提交结果时更新状态
      if (trainingProgramCoursesIds.value.length > 0) {
        await updateTrainingProgramsStatus();
      }
    } else {
      proxy.$modal.msgError(response.message || '手动分班提交失败，请重试');
    }
  } catch (error) {
    console.error("【手动分班】提交异常:", error);
    proxy.$modal.msgError("网络错误或接口异常，提交失败");
  } finally {
    isSubmitting.value = false;
  }
};


/** 提交班级修改（仅修改：studentId传递主键ID，不改变其他功能） */
const submitModifiedClasses = async () => {
  // 筛选有新增学生的班级（逻辑不变）
  const modifiedClasses = classResults.value.filter(classItem => {
    const classKey = classItem.classInfo.id;
    return modifiedClassIds.value.has(classKey);
  });

  if (modifiedClasses.length === 0) {
    proxy.$modal.msgInfo('没有需要提交的修改');
    return;
  }

  try {
    isSubmitting.value = true;

    // 1. 构建提交数据（仅修改studentId的赋值：从student.studentId改为student.id）
    const courseStudentInfoList = modifiedClasses.map(classItem => {
      const targetClassId = classItem.classInfo.id; // 目标班级ID（不变）
      const addedStudentIds = addedStudentsMap.value.get(targetClassId) || [];
      console.log(`班级[${targetClassId}]新增学生学号列表（前端跟踪用，不变）：`, addedStudentIds);

      // 找出新增的学生（逻辑不变）
      const addedStudents = classItem.students.filter(student => {
        const isAdded = addedStudentIds.includes(student.studentId); // 仍用学号判断新增（不改变前端跟踪逻辑）
        if (isAdded) {
          console.log(`新增学生[主键ID:${student.id} | 学号:${student.studentId}]字段（调试用）：`, {
            originalCourseScheduleDetailsId: student.originalCourseScheduleDetailsId,
            currentCourseScheduleDetailsId: student.currentCourseScheduleDetailsId,
            courseScheduleDetailsId: student.courseScheduleDetailsId
          });
        }
        return isAdded;
      });

      // 构建学生提交数据（核心修改：studentId = student.id 主键）
      const courseStudentInfos = addedStudents.map(student => {
        // 兜底逻辑不变（避免后端字段为null报错）
        const originalId = student.originalCourseScheduleDetailsId
            || student.currentCourseScheduleDetailsId
            || 'UNKNOWN_ORIGIN';

        return {
          // 学生基础字段（仅修改studentId！其他字段完全不变）
          id: student.id || '', // 主键ID（原逻辑保留）
          studentId: student.id || '', // 核心修改：传递主键ID给后端（原：student.studentId）
          attendanceScore: student.attendanceScore || null,
          courseDesignScore: student.courseDesignScore || null,
          examScore: student.examScore || null,
          experimentScore: student.experimentScore || null,
          midtermScore: student.midtermScore || null,
          otherScore: student.otherScore || null,
          totalScore: student.totalScore || null,
          isPassed: student.isPassed || null,
          createdAt: student.createdAt || null,
          updatedAt: student.updatedAt || null,
          resitScore: student.resitScore || null,
          gradePoint: student.gradePoint || null,
          enrollmentStatus: student.enrollmentStatus || null,
          enrollmentTime: student.enrollmentTime || null,
          withdrawalTime: student.withdrawalTime || null,

          // 班级关联字段（完全不变）
          courseScheduleDetailsId: targetClassId,
          currentCourseScheduleDetailsId: originalId,
          originalCourseScheduleDetailsId: originalId
        };
      });

      return {
        courseScheduleDetailsId: targetClassId, // 班级维度目标ID（不变）
        courseStudentInfoList: courseStudentInfos // 含主键ID的学生列表（修改后）
      };
    });

    // 过滤空数据（逻辑不变）
    const filteredData = courseStudentInfoList.filter(item =>
        item.courseStudentInfoList.length > 0
    );
    console.log('提交给后端的最终数据（studentId已改为主键）：', filteredData);

    // 2. 调用接口提交（逻辑不变）
    const response = await updateCourseStudentInfoList(filteredData);

    if (response.code === 200) {
      modifiedClassIds.value.clear();
      addedStudentsMap.value.clear();
      proxy.$modal.msgSuccess(`成功提交 ${filteredData.length} 个班级的新增学生！`);
    } else {
      proxy.$modal.msgError(`提交失败：${response.message || '未知错误'}`);
    }
  } catch (error) {
    console.error('【提交班级修改】接口异常：', error);
    proxy.$modal.msgError(`提交失败：${error.message || '网络异常'}`);
  } finally {
    isSubmitting.value = false;
  }
};

// 1. 新增一个方法，专门处理学生首次进入临时班的逻辑
// （在学生从原始班级进入临时班时调用）
const handleStudentEnterTempClass = (student) => {
  // 仅在首次进入临时班时记录原始班级ID
  if (!student.originalCourseScheduleDetailsId) {
    // 保存原始班级ID（这是进入临时班前的班级ID）
    student.originalCourseScheduleDetailsId = student.courseScheduleDetailsId || null;
  }

  // 进入临时班时，更新当前班级ID，但保留原始ID
  return {
    ...student,
    // 临时班ID作为当前课程ID
    courseScheduleDetailsId: 'TEMP_CLASS_ID', // 临时班的ID
    // 原始班级ID存入current字段
    currentCourseScheduleDetailsId: student.originalCourseScheduleDetailsId
  };
};

// ---------------------- 数据加载方法 ----------------------
/** 获取学生姓名映射 */
const fetchStudentNames = async (studentIds) => {
  if (!studentIds || studentIds.length === 0) return;

  try {
    const response = await listStudentManger({studentId: studentIds.join(',')});
    if (response.code === 200 && Array.isArray(response.rows)) {
      response.rows.forEach(student => {
        studentInfoMap.value.set(student.studentId, student.studentName);
      });
    }
  } catch (error) {
    // 失败时用学号作为姓名
    studentIds.forEach(id => studentInfoMap.value.set(id, id));
  }
};

/** 加载培养方案对应的学生 */
const fetchProgramStudents = async () => {
  try {
    const response = await selectStudentInfoListByTrainingProgramIds(trainingProgramIds.value);
    if (response.code === 200 && Array.isArray(response.data)) {
      // 按培养方案ID分组存储
      const groupedData = response.data.reduce((acc, student) => {
        const programId = student.trainingProgramId;
        if (!acc[programId]) acc[programId] = [];
        acc[programId].push(student);
        return acc;
      }, {});

      allProgramStudents.value = groupedData;

      // 校验学生数据完整性
      const studentsWithoutId = response.data.filter(s => !s.studentId && s.studentId !== 0);
      if (studentsWithoutId.length > 0) {
        proxy.$modal.msgError(`加载学生数据异常：${studentsWithoutId.length}个学生缺少学号`);
      }
    }
  } catch (error) {
    console.error("加载培养方案学生失败：", error);
    proxy.$modal.msgError("加载学生数据失败，无法添加学生");
  }
};

/** 查看班级详情 */
const handleViewDetails = (classData) => {
  currentClass.value = classData;
  currentClassStudents.value = [...classData.students];
  showStudentDialog.value = true;
};

/** 查看培养方案学生 */
const handleViewProgramStudents = async (programId) => {
  try {
    // 优先从缓存获取
    if (allProgramStudents.value[programId]) {
      programStudents.value = allProgramStudents.value[programId];
      showProgramStudentDialog.value = true;
      return;
    }

    // 缓存没有则接口获取
    const response = await selectStudentInfoListByTrainingProgramIds([programId]);
    if (response.code === 200) {
      if (response.data?.length) {
        programStudents.value = response.data;
        allProgramStudents.value[programId] = response.data;
        showProgramStudentDialog.value = true;
      } else {
        proxy.$modal.msgInfo('该培养方案暂无学生数据');
      }
    } else {
      proxy.$modal.msgError(response.msg || '获取学生数据失败');
    }
  } catch (error) {
    proxy.$modal.msgError('网络错误，请稍后重试');
  }
};

/** 表格行点击事件（避免误触） */
const handleTableRowClick = () => {
  if (studentTableRef.value) {
    studentTableRef.value.clearSelection();
    currentSelectedStudents.value = [];
  }
};

// ---------------------- 课程与培养方案数据加载 ----------------------
/** 获取课程详情 */
const getCourseDetails = async () => {
  if (!courseId.value) {
    tableData.value = [];
    proxy.$modal.msgWarning('课程ID为空，无法加载课程信息');
    return;
  }

  try {
    const response = await getCourse(courseId.value);
    if (response.code === 200 && response.data) {
      // 校验课程信息完整性
      const hasValidId = response.data.id || response.data.courseId;
      const hasValidName = response.data.courseName || response.data.name;

      if (hasValidId && hasValidName) {
        tableData.value = [{
          ...response.data,
          courseId: response.data.id || response.data.courseId,
          courseName: response.data.courseName || response.data.name,
          grade: Number(selectedGrade.value),
          semester: Number(selectedSemester.value),
          isRequired: response.data.isRequired ? Number(response.data.isRequired) : 0
        }];
      } else {
        tableData.value = [];
        proxy.$modal.msgError(`获取的课程信息无效，缺少${!hasValidId ? 'ID' : '名称'}字段`);
      }
    } else {
      tableData.value = [];
      proxy.$modal.msgError('未找到课程信息（接口返回空）');
    }
  } catch (error) {
    tableData.value = [];
    proxy.$modal.msgError('获取课程信息失败（网络/接口异常）');
  }
};

/** 获取培养方案详情 */
const getTrainingManagementDetails = async () => {
  if (trainingProgramIds.value.length === 0) {
    proxy.$modal.msgWarning('缺少培养方案ID参数，无法加载培养方案详情');
    return;
  }

  try {
    // 批量获取培养方案信息
    const promises = trainingProgramIds.value.map(id => getTrainingManagement(id));
    const results = await Promise.all(promises);

    // 过滤有效数据
    trainingPrograms.value = results.filter(res => {
      const isValid = res.code === 200 && res.data && res.data.id;
      if (!isValid) console.warn(`【加载培养方案】无效数据：ID=${res.config?.params?.id}`);
      return isValid;
    }).map(res => ({
      ...res.data,
      // 统一培养方案类型格式
      cultureProgramType: res.data.cultureProgramType !== undefined
          ? String(res.data.cultureProgramType)
          : res.data.cultureProgramType
    }));

    filteredTrainingManagementList.value = trainingPrograms.value;

    // 加载每个培养方案的学科信息
    if (filteredTrainingManagementList.value.length > 0) {
      const subjectPromises = filteredTrainingManagementList.value.map(
          program => fetchProgramSubjectInfo(program.id)
      );
      await Promise.all(subjectPromises);
    }
  } catch (error) {
    trainingPrograms.value = [];
    filteredTrainingManagementList.value = [];
    proxy.$modal.msgError('获取培养方案信息失败');
  }
};

/** 获取学院列表 */
const getCollegeList = async () => {
  try {
    const res = await listCollege({pageSize: 1000});
    collegeList.value = res.rows || [];
    collegeLoaded.value = true;
  } catch (err) {
    proxy.$modal.msgError("学院数据加载失败");
    collegeLoaded.value = true;
  }
};

// ---------------------- 监听与初始化 ----------------------
/** 监听路由参数变化 */
watch([() => route.query.courseId, () => route.query.grade, () => route.query.semester],
    async (newValues) => {
      const [newCourseId, newGrade, newSemester] = newValues;

      // 课程ID变化：重新加载课程信息
      if (newCourseId !== courseId.value) {
        courseId.value = newCourseId || '';
        await getCourseDetails();
      }

      // 年级/学期变化：更新课程信息中的年级学期
      if (newGrade !== selectedGrade.value || newSemester !== selectedSemester.value) {
        selectedGrade.value = newGrade || '';
        selectedSemester.value = newSemester || '';

        if (tableData.value && tableData.value.length) {
          tableData.value = [{
            ...tableData.value[0],
            grade: Number(selectedGrade.value),
            semester: Number(selectedSemester.value)
          }];
        }
      }
    },
    {immediate: true}
);

/** 监听字典变化（确保标签显示正确） */
watch([semester, grade], () => {
  if (tableData.value && tableData.value.length) {
    tableData.value = [{
      ...tableData.value[0],
      grade: Number(selectedGrade.value),
      semester: Number(selectedSemester.value)
    }];
  }
});

/** 监听添加学生弹窗关闭 */
watch(() => showAddStudentDialog.value, (isOpen) => {
  if (!isOpen) {
    currentSelectedStudents.value = [];
    nextTick(() => {
      studentTableRef.value?.clearSelection();
    });
  }
});

/** 监听班级详情弹窗关闭 */
watch(() => showStudentDialog.value, (isOpen) => {
  if (!isOpen) {
    currentClassStudents.value = [];
  }
});

/** 页面初始化 */
onMounted(async () => {
  try {
    // 1. 获取路由参数
    getQueryParams();

    // 2. 加载基础数据（学院、课程、培养方案）
    await Promise.all([
      getCollegeList(),
      getCourseDetails(),
      getTrainingManagementDetails()
    ]);

    // 3. 加载培养方案学生（用于手动添加）
    if (trainingProgramIds.value.length > 0) {
      await fetchProgramStudents();
    }

    // 4. 加载已有班级数据
    if (courseId.value && selectedSemester.value && selectedGrade.value) {
      try {
        const response = await getCourseScheduleWithStudents(
            courseId.value,
            Number(selectedSemester.value),
            Number(selectedGrade.value)
        );

        if (response.code === 200 && Array.isArray(response.data)) {
          // 使用initStudentOriginalId初始化学生原始ID
          autoClassResults.value = response.data.map(item => ({
            classInfo: item.courseScheduleDetails,
            students: initStudentOriginalId(
                (item.studentDetailedVo || []).map(student => ({
                  ...student,
                  courseScheduleDetailsId: item.courseScheduleDetails.id, // 目标班级ID
                  currentCourseScheduleDetailsId: student.courseScheduleDetailsId || null // 原始ID
                }))
            ),
            maxSize: item.courseScheduleDetails.maxCapacity || formData.maxClassSize
          }));

          // 初始化新增学生记录
          initAddedStudentsMap(autoClassResults.value);

          // 构建学号-姓名映射
          autoClassResults.value.forEach(classItem => {
            classItem.students.forEach(student => {
              studentInfoMap.value.set(student.studentId, student.studentName);
            });
          });
        }
      } catch (error) {
        console.error('【加载已有班级】失败:', error);
        proxy.$modal.msgError('加载已有班级数据失败，不影响新分班操作');
      }
    }
    // 5. 新增：页面加载完成后获取并打印当前学年学期信息
    try {
      const yearTermResponse = await getCurrentYearAndTerm();
      if (yearTermResponse.code === 200) {
        console.log('当前学年学期信息：', yearTermResponse.data);
        // 保存学年标识（dictionaryValue）
        currentAcademicYear.value = yearTermResponse.data.year?.dictionaryValue || '';
      } else {
        console.error('获取当前学年学期信息失败：', yearTermResponse.message || '未知错误');
      }
    } catch (error) {
      console.error('获取当前学年学期信息接口调用异常：', error);
    }
  } catch (error) {
    console.error('【页面初始化】失败:', error);
    proxy.$modal.msgError('页面加载失败，请重试');
  }
});

// ---------------------- 统计计算 ----------------------
/** 总学生数 */
const totalStudents = computed(() => {
  return classResults.value.reduce((total, item) => total + (item.students?.length || 0), 0);
});

/** 班级数量 */
const classCount = computed(() => classResults.value.length);

/** 平均班级人数 */
const averageStudents = computed(() => {
  if (classCount.value === 0) return 0;
  // 四舍五入保留整数
  return Math.round(totalStudents.value / classCount.value);
});

/** 总选课人数（所有培养方案人数之和） */
const totalEnrollmentCount = computed(() => {
  return filteredTrainingManagementList.value.reduce(
      (total, item) => total + (Number(item.amount) || 0),
      0
  );
});
</script>

<style scoped>
/* 选中状态样式 */
.selected-mode {
  border-color: #165DFF !important;
  background-color: #165DFF !important;
  color: #FFFFFF !important;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(22, 93, 255, 0.3) !important;
  transition: all 0.2s ease;
}

/* 未选中按钮样式 */
.form-item .el-button.size-large:not(.selected-mode) {
  border-color: #DCDFE6 !important;
  background-color: #FFFFFF !important;
  color: #606266 !important;
  transition: all 0.2s ease;
}

.form-item .el-button.size-large:not(.selected-mode):hover {
  border-color: #165DFF !important;
  color: #165DFF !important;
  background-color: #F5F7FA !important;
}

/* 按钮基础样式 */
.form-item .el-button.size-large {
  padding: 0.6rem 1.5rem;
  font-size: 1rem;
  min-width: 120px;
}

/* 信息项布局 */
.info-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 8px 0;
}

.major-info-item {
  padding: 4px 0 !important;
}

.info-content {
  display: flex;
  flex-direction: column;
  flex: 1;
  gap: 4px;
}

/* 全局标签与值样式 */
.info-label {
  font-size: 12px;
  color: #666;
}

.info-value {
  font-size: 14px;
  color: #333;
  word-break: break-word;
}

/* 培养方案详情样式 */
.program-info-label {
  font-size: 13px !important;
  font-weight: 500;
}

.program-info-value {
  font-size: 15px !important;
}

.program-info-tip {
  font-size: 15px;
  color: #666;
  margin-top: 1px;
}

.program-dict-tag {
  font-size: 15px !important;
  padding: 2px 8px !important;
}

.program-view-btn {
  font-size: 14px !important;
  padding: 6px 12px !important;
}

/* 操作项样式 */
.action-item {
  justify-content: flex-end;
  padding-top: 12px;
}

/* 基础布局 */
.container {
  padding: 20px;
}

.header h1 {
  font-size: 1.5rem;
  font-weight: 700;
}

.header h3 {
  font-size: 0.875rem;
  color: #666;
  margin-top: 4px;
}

/* 分班规则容器 */
.rule-container {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.rule-header {
  display: flex;
  align-items: center;
  gap: 8px;
  border-bottom: 1px solid #eee;
  padding-bottom: 12px;
}

/* 表单项样式 */
.form-item {
  background: #f9fafb;
  padding: 16px;
  border-radius: 6px;
}

/* 按钮间距与对齐 */
.flex.gap-4 {
  gap: 16px;
}

.flex.justify-end {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

/* 学科信息区域 */
.subject-info-container {
  line-height: 1.2 !important;
  letter-spacing: 0.2px;
  font-size: 14px !important;
}

.subject-info-p {
  margin: 2px 0 !important;
  padding: 0 !important;
  font-size: 14px !important;
}

.subject-info-dir {
  line-height: 1.2 !important;
  margin: 2px 0 !important;
  font-size: 14px !important;
}

.subject-info-container .ml-2 {
  margin-left: 8px !important;
}

/* 通用样式 */
.text-xs {
  font-size: 12px;
}

.text-gray-500 {
  color: #666;
}

.mt-1 {
  margin-top: 4px;
}

.mb-1 {
  margin-bottom: 4px;
}

.mb-2 {
  margin-bottom: 8px;
}

.mb-4 {
  margin-bottom: 16px;
}

.mb-6 {
  margin-bottom: 24px;
}

.mt-4 {
  margin-top: 16px;
}

.mt-8 {
  margin-top: 32px;
}

.mt-0.5 {
  margin-top: 2px !important;
}

/* 卡片样式 */
.el-card {
  margin-bottom: 1.5rem;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.el-card:hover {
  box-shadow: 0 10px 20px 0 rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
  transition: all 0.3s ease;
}

/* 表格样式 */
.el-table {
  width: 100%;
  border: 1px solid #ddd;
  margin-bottom: 20px;
}

/* 提交按钮样式 */
.el-button--primary.size-small {
  background-color: #165DFF !important;
  border-color: #165DFF !important;
  color: #FFFFFF !important;
}

.el-button--primary.size-small:hover {
  background-color: #0E4BDB !important;
  border-color: #0E4BDB !important;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .el-table {
    font-size: 12px;
  }

  .el-col {
    width: 100% !important;
  }

  .program-info-label {
    font-size: 12px !important;
  }

  .program-info-value {
    font-size: 14px !important;
  }
}

/* 操作列按钮优化 */
.el-table-column:last-child .el-button--text {
  padding: 0 5px;
}

.text-gray-400 {
  color: #c0c4cc;
}

.text-green-500 {
  color: #52C41A;
}

.text-orange-500 {
  color: #FAAD14;
}
</style>
